package com.pingsky.apm.agent.bootstrap;

import com.pingsky.apm.agent.api.AgentDir;
import com.pingsky.apm.agent.api.PingSkyClassLoader;
import com.pingsky.apm.agent.api.log.BootLogger;
import com.pingsky.apm.agent.api.util.JarUtil;

import java.lang.instrument.Instrumentation;
import java.lang.reflect.Constructor;
import java.net.URL;
import java.util.List;

/**
 * premain 入口,提供agent初始化功能
 *
 * @author zifeihan
 */
public class PingSkyPremain {

    private final static String LAUNCHER_CLASS = "com.pingsky.apm.agent.core.PingSkyLauncher";

    private final static BootLogger LOGGER = BootLogger.getLogger(PingSkyPremain.class.getName());

    public static void premain(String args, Instrumentation instrumentation) {
        LOGGER.info("pingsky agent starting...");
        try {
            start(instrumentation);
        } catch (Exception e) {
            LOGGER.warn("pingsky agent start filed...");
            System.exit(1);
        }
    }

    private static void start(Instrumentation instrumentation) throws Exception {
        List<URL> urls = JarUtil.resolveLib(AgentDir.getInstance().getLibDir(), new String[]{"jar"});
        ClassLoader classLoader = PingSkyClassLoader.createClassLoader(urls.toArray(new URL[]{}),
                PingSkyPremain.class.getClassLoader());
        Class<?> launch = classLoader.loadClass(LAUNCHER_CLASS);
        Constructor<?> constructor = launch.getDeclaredConstructor(Instrumentation.class);
        constructor.newInstance(instrumentation);
    }
}
